import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
  Card,
  Typography,
  Tag,
  Avatar,
  Button,
  Divider,
  List,
  Space,
  Modal,
  Form,
  Input,
  Upload,
  message,
  Spin,
  Popconfirm,
} from "antd";
import {
  UserOutlined,
  GiftOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  UploadOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { BountyProvider, useBounty } from "./BountyContext";
import "./style.styl";

const { Title, Paragraph } = Typography;
const { TextArea } = Input;

// 悬赏详情内容组件
const BountyDetailContent = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [detail, setDetail] = useState(null);
  const [loading, setLoading] = useState(true);
  const [submitModalVisible, setSubmitModalVisible] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [form] = Form.useForm();

  // 使用bounty上下文
  const {
    getBountyDetail,
    submitBountyResource,
    closeBounty,
    acceptSubmission,
    rejectSubmission,
    deleteBounty,
    currentUser,
  } = useBounty();

  const fetchBountyDetail = async () => {
    setLoading(true);
    try {
      const res = await getBountyDetail(id);
      setDetail(res.data);
    } catch (error) {
      console.error("加载悬赏详情失败:", error);
      message.error("加载悬赏详情失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchBountyDetail();
  }, [id]);

  const handleSubmitResource = async (values) => {
    setSubmitting(true);
    try {
      const formData = {
        description: values.description,
        resourceLink: values.resourceLink,
        fileUrl:
          values.file && values.file.length > 0
            ? "https://example.com/uploads/" + values.file[0].name
            : null,
      };

      await submitBountyResource(id, formData);
      message.success("资源提交成功，等待审核");
      setSubmitModalVisible(false);
      fetchBountyDetail();
    } catch (error) {
      console.error("提交资源失败:", error);
      message.error("提交失败，请稍后重试");
    } finally {
      setSubmitting(false);
    }
  };

  const handleCloseBounty = async () => {
    try {
      await closeBounty(id);
      message.success("悬赏任务已关闭");
      fetchBountyDetail();
    } catch (error) {
      console.error("关闭悬赏任务失败:", error);
      message.error("操作失败，请稍后重试");
    }
  };

  const handleAcceptSubmission = async (submissionId) => {
    try {
      await acceptSubmission(id, submissionId);
      message.success("已采纳该提交");
      fetchBountyDetail();
    } catch (error) {
      console.error("采纳提交失败:", error);
      message.error("操作失败，请稍后重试");
    }
  };

  const handleRejectSubmission = async (submissionId) => {
    try {
      await rejectSubmission(id, submissionId);
      message.success("已驳回该提交");
      fetchBountyDetail();
    } catch (error) {
      console.error("驳回提交失败:", error);
      message.error("操作失败，请稍后重试");
    }
  };

  const handleDeleteBounty = async () => {
    try {
      await deleteBounty(id);
      message.success("悬赏任务已删除");
      navigate("/community/bounty");
    } catch (error) {
      console.error("删除悬赏任务失败:", error);
      message.error("删除失败，请稍后重试");
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case "active":
        return "green";
      case "completed":
        return "blue";
      case "expired":
        return "red";
      default:
        return "default";
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case "active":
        return "进行中";
      case "completed":
        return "已完成";
      case "expired":
        return "已过期";
      default:
        return "未知状态";
    }
  };

  const getSubmissionStatusColor = (status) => {
    switch (status) {
      case "pending":
        return "gold";
      case "accepted":
        return "green";
      case "rejected":
        return "red";
      default:
        return "default";
    }
  };

  const getSubmissionStatusText = (status) => {
    switch (status) {
      case "pending":
        return "审核中";
      case "accepted":
        return "已采纳";
      case "rejected":
        return "已驳回";
      default:
        return "未知状态";
    }
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" tip="数据加载中..." />
      </div>
    );
  }

  if (!detail) {
    return (
      <div className="not-found">
        <Title level={3}>悬赏任务不存在或已被删除</Title>
        <Button type="primary" onClick={() => navigate("/community/bounty")}>
          返回悬赏列表
        </Button>
      </div>
    );
  }

  // 是否为任务发布者
  const isPublisher =
    detail.publisher && detail.publisher.id === currentUser.id;

  // 任务是否处于进行中状态
  const isActive = detail.status === "active";

  return (
    <div className="bounty-detail-container">
      <Card className="bounty-detail-card">
        <div className="bounty-header">
          <div className="bounty-title-section">
            <Title level={3}>{detail.title}</Title>
            <Space>
              <Tag color={getStatusColor(detail.status)}>
                {getStatusText(detail.status)}
              </Tag>
              <Tag icon={<GiftOutlined />} color="purple">
                奖励: {detail.reward} 魔力值
              </Tag>
            </Space>
          </div>

          <div className="bounty-actions">
            {isActive && !isPublisher && (
              <Button
                type="primary"
                onClick={() => setSubmitModalVisible(true)}
              >
                提交资源
              </Button>
            )}

            {isActive && isPublisher && (
              <Space>
                <Popconfirm
                  title="确定要关闭该悬赏任务吗？"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={handleCloseBounty}
                >
                  <Button>关闭任务</Button>
                </Popconfirm>

                <Popconfirm
                  title="确定要删除该悬赏任务吗？"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={handleDeleteBounty}
                >
                  <Button danger icon={<DeleteOutlined />}>
                    删除任务
                  </Button>
                </Popconfirm>
              </Space>
            )}
          </div>
        </div>

        <div className="publisher-info">
          <Avatar size="small" icon={<UserOutlined />} />
          <span className="publisher-name">
            {detail.publisher?.username || "未知用户"}
          </span>
          <span className="publish-time">
            <ClockCircleOutlined /> 发布于{" "}
            {new Date(detail.createdAt).toLocaleString()}
          </span>
        </div>

        <Divider orientation="left">需求描述</Divider>
        <div className="bounty-description">
          <Paragraph>{detail.description}</Paragraph>
        </div>

        <Divider orientation="left">提交记录</Divider>
        {detail.submissions && detail.submissions.length > 0 ? (
          <List
            className="submission-list"
            itemLayout="horizontal"
            dataSource={detail.submissions}
            renderItem={(item) => (
              <List.Item
                actions={
                  isPublisher && isActive && item.status === "pending"
                    ? [
                        <Button
                          type="primary"
                          size="small"
                          icon={<CheckCircleOutlined />}
                          onClick={() => handleAcceptSubmission(item.id)}
                        >
                          采纳
                        </Button>,
                        <Button
                          danger
                          size="small"
                          icon={<CloseCircleOutlined />}
                          onClick={() => handleRejectSubmission(item.id)}
                        >
                          驳回
                        </Button>,
                      ]
                    : []
                }
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<UserOutlined />} />}
                  title={
                    <div className="submission-title">
                      <span>{item.submitter?.username || "未知用户"}</span>
                      <Tag color={getSubmissionStatusColor(item.status)}>
                        {getSubmissionStatusText(item.status)}
                      </Tag>
                    </div>
                  }
                  description={
                    <div className="submission-details">
                      <div className="submission-time">
                        提交时间: {new Date(item.createdAt).toLocaleString()}
                      </div>
                      <div className="submission-description">
                        {item.description}
                      </div>
                      {item.resourceLink && (
                        <div className="submission-link">
                          资源链接:{" "}
                          <a
                            href={item.resourceLink}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            {item.resourceLink}
                          </a>
                        </div>
                      )}
                      {item.fileUrl && (
                        <div className="submission-file">
                          附件:{" "}
                          <a
                            href={item.fileUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            查看附件
                          </a>
                        </div>
                      )}
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        ) : (
          <div className="empty-submissions">
            <Paragraph>暂无提交记录</Paragraph>
          </div>
        )}
      </Card>

      {/* 提交资源弹窗 */}
      <Modal
        title="提交资源"
        open={submitModalVisible}
        onCancel={() => setSubmitModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmitResource}>
          <Form.Item
            name="description"
            label="提交说明"
            rules={[{ required: true, message: "请输入提交说明" }]}
          >
            <TextArea
              placeholder="请描述您提交的资源..."
              rows={4}
              maxLength={200}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="resourceLink"
            label="资源链接"
            rules={[
              {
                type: "url",
                message: "请输入有效的URL链接",
              },
            ]}
          >
            <Input placeholder="请输入资源下载链接(可选)" />
          </Form.Item>

          <Form.Item name="file" label="上传文件(可选)">
            <Upload maxCount={1} beforeUpload={() => false} listType="text">
              <Button icon={<UploadOutlined />}>点击上传</Button>
            </Upload>
          </Form.Item>

          <div className="form-actions">
            <Button onClick={() => setSubmitModalVisible(false)}>取消</Button>
            <Button type="primary" htmlType="submit" loading={submitting}>
              提交资源
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

// 主组件，包含Provider
// const BountyDetail = () => {
//   return (
//     <BountyProvider>
//       <BountyDetailContent />
//     </BountyProvider>
//   );
// };

export default BountyDetailContent;
